/*
 * Copyrignt (c) xuzeshui.com. All Rights Reserved.
 * Author: Xiaobao Zeng<zengxiaobao@skyworth.com>
 * Created Time: 2017-07-25 09:59:31
 * Last Modified: 2017-07-28 14:31:32
 * File Name: passport.go
 * Description:
 */

package passport

// package main

import (
	"fmt"
	// "time"

	"crypto/tls"
	//"errors"

	"qkcoupon/errorcode"
	"qkcoupon/models"

	"doubimeizhi.com/utility"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/httplib"
	log "github.com/cihub/seelog"
)

var (
	pphost   string = "passport.app.qkier.com"
	ppAppkey string = "140a6d51d67c477e83cd91a241678824"
	ppSecret string = "88366f9fad954828a194f3232a78a471"
)

type AKSignResp struct {
	Code         int    `json:"code"`
	Msg          string `json:"msg"`
	Userid       string `json:"userid"`
	ExpireSecond int    `json:"expire_second"`
}

/*
   UserInfo的基本信息结构
*/
type UserInfo struct {
	Code       int    `json:"code"`
	Msg        string `json:"msg"`
	UserId     string `json:"userid"`
	Mobile     string `json:"mobile"`      //联系手机号
	NickName   string `json:"nick_name"`   //昵称
	Gender     int8   `json:"gender"`      //性别
	Avatar     string `json:"avatar"`      //头像地址
	Slogan     string `json:"slogan"`      //个性签名
	Birthday   string `json:"birthday"`    //生日
	Idcard     string `json:"idcard"`      //身份证号码
	RegionCode string `json:"region_code"` //用户的地址行政编码
	RegionAddr string `json:"region_addr"` //用户的详细地址,不包含region_code
	InviteCode string `json:"invite_code"` //自己的邀请码
}

func GetUseridByAccessToeknFromPassport(accessToken string) (string, int, bool) {
	nusb := utility.NewURLSignBuilder(ppAppkey, ppSecret, fmt.Sprintf("https://%s/v1/account/accesstoken/validate", pphost))
	nusb.SetURLParam("ak", accessToken)
	reqURL := nusb.BuildURL()
	b := httplib.Get(reqURL)
	b.SetHost(pphost)
	b.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
	resp := &AKSignResp{}
	if err := b.ToJSON(resp); err != nil {
		log.Errorf("GetUseridByAccessToeknFromPassport ,request passport fail,err:%s", err.Error())
		return "", 0, false
	}

	if resp == nil || resp.Code != 0 {
		log.Infof("GetUseridByAccessToeknFromPassport, invalidate ak fail. resp:%v", resp)
		log.Warnf("GetUseridByAccessToeknFromPassport err. reqURL:%s", reqURL)
		return "", 0, false
	}

	return resp.Userid, resp.ExpireSecond, true
}

func IsValidAccessTokenForUserid(accessToken, uid string) bool {
	if "" == accessToken || "" == uid {
		return false
	}
	if userid, _, ok := GetUseridByAccessToeknFromPassport(accessToken); ok && userid == uid {
		return true
	}
	return false
}

/*
 *@note 通过用户ID获取用户信息
 *@param mode_id: 洗衣模式编号
 *@return *QSQkCouponUserProfile: 洗衣机信息
 */
func GetUserProfileByUID(uid string) (*models.PQSQkCouponUserProfile, uint) {
	nusb := utility.NewURLSignBuilder(ppAppkey, ppSecret, fmt.Sprintf("https://%s/v1/userinfo/get", pphost))
	nusb.SetURLParam("uid", uid)
	reqURL := nusb.BuildURL()
	b := httplib.Get(reqURL)
	b.SetHost(pphost)
	b.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})

	up := &models.PQSQkCouponUserProfile{}
	if err := b.ToJSON(up); err != nil {
		log.Warn(err.Error())
		return nil, errorcode.EC_GL_REMOTE_REQ_FAIL
	}

	code := uint(up.Code)
	if code != errorcode.EC_GL_SUCCESS {
		log.Warnf("GetUserProfileByUID err. reqURL:%s", reqURL)
		return nil, code
	}

	return up, errorcode.EC_GL_SUCCESS
}

/*
 *@note 通过手机号获取用户信息
 *@param mode_id: 洗衣模式编号
 *@return *QSQkCouponUserProfile: 洗衣机信息
 */
func GetUserProfileByAccount(mobile string) (*models.PQSQkCouponUserProfile, uint) {

	nusb := utility.NewURLSignBuilder(ppAppkey, ppSecret, fmt.Sprintf("https://%s/v1/userinfo/get", pphost))
	nusb.SetURLParam("account_type", "mobile")
	nusb.SetURLParam("account", mobile)
	reqURL := nusb.BuildURL()
	b := httplib.Get(reqURL)
	b.SetHost(pphost)
	b.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})

	up := &models.PQSQkCouponUserProfile{}
	if err := b.ToJSON(up); err != nil {
		log.Warn(err.Error())
		return nil, errorcode.EC_GL_REMOTE_REQ_FAIL
	}

	code := uint(up.Code)
	if code != errorcode.EC_GL_SUCCESS {
		return nil, code
	}

	return up, errorcode.EC_GL_SUCCESS
}

func init() {
	pphost = beego.AppConfig.DefaultString("backsvr::ppapi_host", "passport.app.qkier.com")
	ppAppkey = beego.AppConfig.DefaultString("backsvr::ppapi_appkey", "140a6d51d67c477e83cd91a241678824")
	ppSecret = beego.AppConfig.DefaultString("backsvr::ppapi_secret", "88366f9fad954828a194f3232a78a471")
}

/*
func main() {
        // GetUseridByAccessToeknFromPassport("eVhI8_2tQb-uW647IpZ9sA1")
        uiInfo := QueryUserInfo("5de096ee4e7148b5abaa8dad31cb009c")
        fmt.Println(uiInfo)
        uiInfo2 := QueryUserInfoByMobile("13297984197")
        fmt.Println(uiInfo2)
}
*/
